package servlet.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import pojo.Book;
import pojo.Book2;
import service.ConvertBooksType;
import service.SearchIndexpagere;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/searchclass2")
public class SearchClassServlet2 extends HttpServlet {
    private ConvertBooksType convertBooksType = new ConvertBooksType();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应对象类型
        resp.setContentType("application/json;charset=utf-8");
        // 从请求中获取参数
        String bookType = req.getParameter("bookType"); // 获取图书分类名称
        System.out.println(bookType);
        SearchIndexpagere searchIndexpagere = new SearchIndexpagere();
        List<Book2> book2s = searchIndexpagere.selectClassBook2(bookType);
        //当前页数
        String currentPage = req.getParameter("currentPage");
        //每页展示的数据
        String pageSize = req.getParameter("pageSize");
        // 转换currentPage和pageSize为整数
        int page = Integer.parseInt(currentPage);
        int size = Integer.parseInt(pageSize);
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, book2s.size());
        List<Book2> currentPageBooks = book2s.subList(startIndex, endIndex);
        if (currentPageBooks.isEmpty()){
            System.out.println("空");
            Book book = new Book();
            book.setName("无");
            String jsonString1 = JSON.toJSONString(book);
            PrintWriter writer = resp.getWriter();
            writer.write(jsonString1);
        }else {
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("booklist", currentPageBooks); // 添加books列表
            jsonResponse.put("size", book2s.size()); // 添加books大小信息
            String jsonString2 = jsonResponse.toJSONString();
            PrintWriter writer = resp.getWriter();
            writer.write(jsonString2);
            writer.close();
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
